package com.app.utils;

import android.Manifest;
import android.content.Intent;
import android.text.TextUtils;

import com.app.application.MyApplication;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.lepu.app.fun.market.WebViewHstActivity;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.main.permission.PermissionUtil;
import com.lepu.app.main.permission.callback.PermissionResultCallBack;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.pasm.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class MyStoreUtil implements AsyncRequest {

	private static final String REQUEST_MARKET_SCORE 	= "request_market_score";
	private static final String REQUEST_MARKET_ALL 		= "request_market_all";
	private static final String REQUEST_MARKET_ORDER 	= "request_market_order";
	private static final String REQUEST_ORDER 			= "request_order";

	private static MyStoreUtil mInstance = null;
	private BaseFragmentActivity mBaseFragmentActivity = null;
	private String mJumpUrl = "";
	public String mAppString = "";

	public enum RequestType{
		MARKET_SCORE,
		MARKET_ALL,
		MARKET_ORDER
	}

	private MyStoreUtil()
	{

	}

	public static MyStoreUtil getInstance()
	{
		if(mInstance == null)
		{
			mInstance = new MyStoreUtil();
		}
		return mInstance;
	}

	private void clearVariable()
	{
		mJumpUrl = "";
	}

	//================================================================================
	private void checkPermisson(final BaseFragmentActivity baseFragmentActivity
			, final String gotoUrl, final RequestType type) {
		PermissionUtil.getInstance().request(baseFragmentActivity, new String[]{Manifest.permission.READ_PHONE_STATE,
				},
				new PermissionResultCallBack() {
					@Override
					public void onPermissionGranted() {
						//
						if(type == RequestType.MARKET_SCORE){
							requestMoneyMarketSrc(baseFragmentActivity,gotoUrl);
						}else if (type == RequestType.MARKET_ALL){
							requestAllMarketSrc(baseFragmentActivity,gotoUrl);
						}else if (type == RequestType.MARKET_ORDER){
							requestMarketOrderSrc(baseFragmentActivity, gotoUrl);
						}
					}

					@Override
					public void onPermissionGranted(String... permissions) {
						if (permissions == null || permissions.length == 0) {
						}
					}

					@Override
					public void onPermissionDenied(String... permissions) {

					}

					@Override
					public void onRationalShow(String... permissions) {
						if (permissions != null) {
							UIHelper.showToast(baseFragmentActivity, R.string.permission_tip);
							PermissionUtil.openSettingActivity(baseFragmentActivity);
						}
					}
				});
	}

	/***
	 * 请求积分商城
	 * @param baseFragmentActivity
	 */
	public void requestMoneyMarket(BaseFragmentActivity baseFragmentActivity, String gotoUrl)
	{
		checkPermisson(baseFragmentActivity, gotoUrl, RequestType.MARKET_SCORE);
	}

	private void requestMoneyMarketSrc(BaseFragmentActivity baseFragmentActivity,String gotoUrl)
	{
		boolean flag = LoginUtil
				.jumpLogin(baseFragmentActivity);
		if (!flag) {

			clearVariable();
			mBaseFragmentActivity = baseFragmentActivity;
			mJumpUrl = gotoUrl;

			Map<String, Object> map = new HashMap<String, Object>();
			JSONObject params = new JSONObject();

			try {
				params.put("DeviceID", Setting.DEVICEID);
				params.put("ApplicationID", Setting.APPLICATIONID);

				params.put("UserID", LoginUtil.getUserId());
				params.put("LoginToken", LoginUtil.getLoginToken());

				params.put("OS", "android");
				params.put("Osversion",
						AppManager.getDeviceModel(mBaseFragmentActivity));
				params.put("Resolution", "");
				params.put("DeviceSN",
						AppManager.getDeviceUniqueId(mBaseFragmentActivity));
			} catch (Exception e) {
			}
			map.put("ht", params);

			mBaseFragmentActivity.showProgressDialog();
			ApiClient.http_post_main(Setting.getMarketBindUrl(), map, null, this, REQUEST_MARKET_SCORE, true);
		}
	}

	/***
	 * 请求全商城
	 * @param baseFragmentActivity
	 */
	public void requestAllMarket(BaseFragmentActivity baseFragmentActivity,String gotoUrl)
	{
		checkPermisson(baseFragmentActivity,gotoUrl,RequestType.MARKET_ALL);
	}

	private void requestAllMarketSrc(BaseFragmentActivity baseFragmentActivity,String gotoUrl)
	{
		boolean flag = LoginUtil.jumpLogin(baseFragmentActivity);
		if(!flag)
		{
			clearVariable();
			mBaseFragmentActivity = baseFragmentActivity;
			mJumpUrl = gotoUrl;

			Map<String, Object> map = new HashMap<String, Object>();
			JSONObject params = new JSONObject();

			try {
				params.put("DeviceID", Setting.DEVICEID);
				params.put("ApplicationID", Setting.APPLICATIONID);

				params.put("UserID", LoginUtil.getUserId());
				params.put("LoginToken", LoginUtil.getLoginToken());

				params.put("OS", "android");
				params.put("Osversion",
						AppManager.getDeviceModel(mBaseFragmentActivity));
				params.put("Resolution", "");
				params.put("DeviceSN",
						AppManager.getDeviceUniqueId(mBaseFragmentActivity));

				params.put("MethodName", "special_channel.auth.whole_check");
			} catch (Exception e) {
			}
			map.put("ht", params);

			mBaseFragmentActivity.showProgressDialog();
			ApiClient.http_post_main(Setting.getHealthMarketBindUrl(), map, null, this, REQUEST_MARKET_ALL, true);
		}
	}

	/***
	 * 请求商城订单
	 * @param baseFragmentActivity
	 */
	public void requestMarketOrder(BaseFragmentActivity baseFragmentActivity,String gotoUrl)
	{
		checkPermisson(baseFragmentActivity,gotoUrl,RequestType.MARKET_ORDER);
	}

	private void requestMarketOrderSrc(BaseFragmentActivity baseFragmentActivity,String gotoUrl)
	{
		boolean flag = LoginUtil.jumpLogin(baseFragmentActivity);
		if(!flag)
		{
			clearVariable();
			mBaseFragmentActivity = baseFragmentActivity;
			mJumpUrl = gotoUrl;

			Map<String, Object> map = new HashMap<String, Object>();
			JSONObject params = new JSONObject();

			try {
				params.put("DeviceID", Setting.DEVICEID);
				params.put("ApplicationID", Setting.APPLICATIONID);

				params.put("UserID", LoginUtil.getUserId());
				params.put("LoginToken", LoginUtil.getLoginToken());

				params.put("OS", "android");
				params.put("Osversion",
						AppManager.getDeviceModel(mBaseFragmentActivity));
				params.put("Resolution", "");
				params.put("DeviceSN",
						AppManager.getDeviceUniqueId(mBaseFragmentActivity));

				params.put("MethodName", "special_channel.auth.whole_check");
			} catch (Exception e) {
			}
			map.put("ht", params);

			mBaseFragmentActivity.showProgressDialog();
			ApiClient.http_post_main(Setting.getHealthMarketBindUrl(), map, null, this, REQUEST_MARKET_ORDER, true);
		}
	}

	public void requestSign(BaseFragmentActivity baseFragmentActivity) {
		boolean flag = LoginUtil
				.jumpLogin(baseFragmentActivity);
		if (!flag) {

			clearVariable();
			mBaseFragmentActivity = baseFragmentActivity;

			String url = Setting.getHealthMarketBindUrl();

			Map<String, Object> map = new HashMap<String, Object>();
			JSONObject params = new JSONObject();

			try {
				params.put("DeviceID", Setting.DEVICEID);
				params.put("ApplicationID", Setting.APPLICATIONID);

				LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
				params.put("UserID", loginInfo.UserID);
				params.put("LoginToken", loginInfo.LoginToken);

				params.put("OS", "android");
				params.put("Osversion",
						AppManager.getDeviceModel(MainTabActivity.getInstance()));
				params.put("Resolution", "");
				params.put("DeviceSN",
						AppManager.getDeviceUniqueId(MainTabActivity.getInstance()));

				params.put("MethodName", "special_channel.order_center.summary");// test
			} catch (Exception e) {
			}
			map.put("ht", params);

			mBaseFragmentActivity.showProgressDialog();
			ApiClient.http_post_main(url, map, null, this, REQUEST_ORDER, true);
		}

	}


	//================================================================================

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_MARKET_ALL) || object.equals(REQUEST_MARKET_ORDER)) {
			LogUtilBase.LogD(null, "REQUEST_MARKET_ALL success");

			mBaseFragmentActivity.hideProgressDialog();

			try {
				JSONObject jsonObject = new JSONObject((String) data);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				JSONObject dataObject = (JSONObject) obj1.get("DetailInfo");

				String baseUrl = "";
				if(TextUtils.isEmpty(mJumpUrl)) {
					if (object.equals(REQUEST_MARKET_ALL)) {
						baseUrl = IConstants.HSTORDERCENTER_MARKET;
					}else {
						baseUrl = IConstants.HSTORDERCENTER_MARKET_ORDER;
					}
				}else{
					baseUrl = mJumpUrl;
					if(baseUrl.contains("?")){
						baseUrl += "&";
					}else{
						baseUrl += "?";
					}
				}
				String AppString = dataObject.getString("AppString");
				//test
//				try {
//					AppString = URLEncoder.encode(AppString, "utf-8");
//				} catch (UnsupportedEncodingException e) {
//					e.printStackTrace();
//				}

				Intent intentStore = new Intent(mBaseFragmentActivity,
						WebViewHstActivity.class);
				intentStore.putExtra("url", baseUrl + AppString);
				//intentStore.putExtra("title", "健康商场");
				intentStore.putExtra("is_health_market",true);
				intentStore.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				mBaseFragmentActivity.startActivity(intentStore, true);

			} catch (JSONException e) {
				e.printStackTrace();
			}
		} else if (object.equals(REQUEST_MARKET_SCORE)) {
			LogUtilBase.LogD(null, "REQUEST_MARKET_SCORE success");

			mBaseFragmentActivity.hideProgressDialog();

			try {
				JSONObject jsonObject = new JSONObject((String) data);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				JSONObject dataObject = (JSONObject) obj1.get("DetailInfo");

				LoginInfo loginInfo = MyApplication.getInstance()
						.getLoginInfo();
				loginInfo.HSTAccessToken = dataObject
						.optString("HSTAccessToken");
				loginInfo.HSTAccessTokenExpireTime = dataObject
						.optString("HSTAccessTokenExpireTime");
				LoginInfo.saveLoginInfo(mBaseFragmentActivity, loginInfo);

				StringBuffer sb = new StringBuffer();

				if(TextUtils.isEmpty(mJumpUrl))
				{
					sb.append(IConstants.HSTSHIP);
				}else{
					sb.append(mJumpUrl);

					if(mJumpUrl.contains("?")){
						sb.append("&");
					}else{
						sb.append("?");
					}
				}

				sb.append("ApplicationID=");
				sb.append(Setting.APPLICATIONID);
				sb.append("&DeviceID=");
				sb.append(Setting.DEVICEID);
				sb.append("&UserID=");
				sb.append(LoginUtil.getUserId());
				sb.append("&AccessToken=");
				sb.append(MyApplication.getInstance().getLoginInfo().HSTAccessToken);

				Intent intent = new Intent(mBaseFragmentActivity,
						WebViewHstActivity.class);
				intent.putExtra("url", sb.toString());
				intent.putExtra("show_need_right_view", true);
				intent.putExtra("is_jifen_store", true);

				mBaseFragmentActivity.startActivity(intent, true);

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}else if (object.equals(REQUEST_ORDER)) {
			mBaseFragmentActivity.hideProgressDialog();
			try {
				JSONObject jsonObject = new JSONObject((String) data);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				JSONObject dataObject = (JSONObject) obj1.get("DetailInfo");

				mAppString = dataObject.getString("AppString");

				LoginInfo loginInfo = MyApplication.getInstance()
						.getLoginInfo();
				loginInfo.HSTAccessToken = dataObject
						.optString("HSTAccessToken");
				loginInfo.HSTAccessTokenExpireTime = dataObject
						.optString("HSTAccessTokenExpireTime");

				LoginInfo.saveLoginInfo(mBaseFragmentActivity, loginInfo);

				Intent intent4 = new Intent(mBaseFragmentActivity, WebViewHstActivity.class);
				intent4.putExtra("url", IConstants.HSTORDERCENTER + mAppString);
				// intent4.putExtra("title", "兑换记录");
				intent4.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				mBaseFragmentActivity.startActivity(intent4, true);

			} catch (Exception e) {

			}
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String data) {
		if (object.equals(REQUEST_MARKET_ALL)) {
			LogUtilBase.LogD(null, "REQUEST_MARKET_ALL fail");
			mBaseFragmentActivity.hideProgressDialog();
		} else if (object.equals(REQUEST_MARKET_SCORE)) {
			LogUtilBase.LogD(null, "REQUEST_MARKET_SCORE fail");
			mBaseFragmentActivity.hideProgressDialog();
		}else if (object.equals(REQUEST_ORDER)) {
			LogUtilBase.LogD(null, "REQUEST_ORDER fail");
			mBaseFragmentActivity.hideProgressDialog();
		}
	}

}
